<?php

namespace App\Common\Helpers;

use Mine\MineRequest;

class UrlHelper
{
    public static function url(string $url, array $params = [], string $domain = ''): string
    {
        $request = container()->get(MineRequest::class);

        if (!empty($params)) {
            $query = http_build_query($params);
        } else {
            $query = '';
        }

        $url = ltrim($url,'/');
        $url = rtrim($url,'/');

        if (empty($domain)) {
            $scheme = $request->getUri()->getScheme() ?? 'http';
            $host = $request->getUri()->getHost() ?? '127.0.0.1';
            $port = $request->getUri()->getPort() ;
            if (is_null($port) || $port == 80 || $port == 443) {
                $domain = "{$scheme}://{$host}/{$url}";
            } else {
                $domain = "{$scheme}://{$host}:{$port}/{$url}";
            }
        } else {
            $domain = $domain . '/' . $url;
        }

        if(!empty($query)){
            return $domain . '?' . $query;
        }
        return $domain;
    }
}